<template>
	<div class="app-container">
		<div ref="box1" class="flex-center margin-bottom-10">
			<el-radio-group v-model="searchParams.auditState" size="medium" class="item-gap" @change="onStateChange">
				<el-radio-button v-for="item in noticeStateList" :key="item.id" :label="item.id">
					<el-badge v-if="item.id <= 3 && item.count > 0" :value="item.count" :max="99">
						<span class="margin-right-20">{{ item.name }}</span>
					</el-badge>
					<div v-else class="margin-right-10" style="padding-bottom: 2px;">{{ item.name }}</div>
				</el-radio-button>
			</el-radio-group>
		</div>
		<jk-operation-card ref="box2" class="margin-bottom-10">
			<div class="flex-between-center-wrap">
				<div class="flex-start-center-wrap">
					<!--<jk-add-button :permission-prefix="prefix" class="margin-5-0 item-gap" @click="onAddBtn"></jk-add-button>-->
					<!--<jk-report-button :permission-prefix="prefix" class="margin-5-0" :loading="exportLoading" @click="onReportBtn"></jk-report-button>-->
					<!--<jk-button class="margin-5-0" :loading="exportLoading" @click="onReportBtn">导出</jk-button>-->
				</div>
				<div class="flex-end-center-wrap">
					<jk-select v-model="searchParams.workshopId" :option-list="workshopList" :clearable="false" placeholder="区域" class="search-bar-item-size2 margin-5-0 item-gap"></jk-select>
					<jk-select v-model="searchParams.processCode" :clearable="true" value-key-name="code" :option-list="processList" placeholder="工序" class="search-bar-item-size1 margin-5-0 item-gap"></jk-select>
					<el-checkbox v-model="searchParams.ifTest" label="试产打样" border class="item-gap" size="small"></el-checkbox>
					<jk-search-input v-model="searchParams.productNameOrCode" placeholder="品种编号或名称" size="small" class="search-bar-item-size3 margin-5-0 item-gap" clearable @on-enter="onSearchBtn" />
					<jk-search-input v-model="searchParams.code" placeholder="生产通知单号" size="small" class="search-bar-item-size3 margin-5-0 item-gap" clearable @on-enter="onSearchBtn" />
					<jk-search-button class="item-gap" @click="onSearchBtn"></jk-search-button>
					<jk-more-search @on-confirm="onSearchBtn" @on-reset="onResetSearchBtn">
						<el-row :gutter="16" class="flex-start-center-wrap">
							<el-col :span="12">
								<jk-search-input v-model="moreSearchParams.batchCode" placeholder="批号" size="small" class="width-100-percent margin-5-0" clearable @on-enter="onSearchBtn" />
							</el-col>
							<el-col :span="12">
								<jk-search-input v-model="moreSearchParams.code" placeholder="通知单号" size="small" class="width-100-percent margin-5-0" clearable @on-enter="onSearchBtn" />
							</el-col>
							<el-col :span="12">
								<jk-select v-model="moreSearchParams.priorityId" :option-list="priorityList" placeholder="优先级" clearable size="small" class="margin-5-0 width-100-percent"></jk-select>
							</el-col>
						</el-row>
					</jk-more-search>
				</div>
			</div>
		</jk-operation-card>

		<jk-card>
			<jk-table :loading="tableLoading" :data="tableData" :height="tableHeight - 44">
				<vxe-column
					v-for="(item, index) in tableColumnList"
					:key="index"
					:title="item.title"
					:align="item.align"
					:field="item.keyName"
					:sortable="item.sortable"
					:fixed="item.fixed ? item.fixed : ''"
					:min-width="item.minWidth"
					:width="item.width"
				>
					<template slot-scope="scope">
						<span v-if="item.keyName === 'code'" class="link-style" @click="onDetailBtn(scope.row)">{{ scope.row.code }}</span>
						<span v-else-if="item.keyName === 'ifTest'">{{ scope.row.ifTest ? '试产打样' : '正式生产' }}</span>
						<jk-state-bar v-else-if="item.keyName === 'priorityName'" :state="scope.row.priorityId" :state-list="priorityList"></jk-state-bar>
						<jk-state-bar v-else-if="item.keyName === 'auditState'" :state="scope.row.auditState" :state-list="noticeStateList"></jk-state-bar>
						<div v-else-if="item.keyName === 'machineList'">{{ scope.row.prdNoticeMachineList ? scope.row.prdNoticeMachineList.filter(x => [1, 2, 3].includes(x.openingState)).map(x => x.machineName).join(',') : '' }}</div>
						<span v-else>{{ scope.row[item.keyName] }}</span>
					</template>
				</vxe-column>
				<vxe-column title="操作" align="center" fixed="right" :width="250">
					<template slot-scope="scope">
						<div class="flex-center">
							<jk-button :disabled="scope.row.auditState !== 0" icon="el-icon-s-flag" class="item-gap" size="mini" type="primary" @click="onDropdownChange('RELEASE', scope.row)">下达</jk-button>
							<jk-button icon="el-icon-edit" class="item-gap" size="mini" type="success" @click="onEditBtn(scope.row)">编辑</jk-button>
							<el-dropdown trigger="click" @command="onDropdownChange($event, scope.row)">
								<el-button type="primary" size="mini" class="el-dropdown-link">
									更多<i class="el-icon-arrow-down el-icon--right"></i>
								</el-button>
								<el-dropdown-menu slot="dropdown">
									<el-dropdown-item
										v-for="(item) in dropdownOption"
										:key="item.code"
										:command="item.code"
										:disabled="item.allowState || item.allowState === 0 ? scope.row.auditState !== item.allowState : false"
										:style="{display: !item.isShow ? 'none' : 'block'}"
									>
										<span :class="`${item.icon} item-gap`"></span>
										<span>{{ item.name }}</span>
									</el-dropdown-item>
								</el-dropdown-menu>
							</el-dropdown>
						</div>
					</template>
				</vxe-column>
			</jk-table>

			<!-- 分页组件 -->
			<footer ref="box2" class="flex-end-center margin-top-10">
				<jk-page
					:page-index="searchParams.pageNo"
					:page-sizes="searchParams.pageSizes"
					:page-size="searchParams.pageSize"
					:total="totalCount"
					@on-change="onPageChange"
				/>
			</footer>
		</jk-card>
	</div>
</template>

<script>
    import calHeight from '/src/mixins/cal-table-height';
    import { pageConfig } from '/src/utils/jk/jk-tool';
    import {
        productionProcessPrdNoticePage,
        productionProcessPrdNoticeRelease,
        productionProcessPrdNoticeClearRelease,
        productionProcessPrdNoticeComplete,
        productionProcessPrdNoticeClearComplete,
        productionProcessPrdNoticeDelete,
        productionProcessPrdNoticeGetStateCount
    } from '/src/api/production/xsNotice';
    import getMenuColumn from '../../../mixins/getMenuColumn';
    import handlerCache from '../../../mixins/handler-cache';
    import {
        noticeStateList,
        orderPriorityList,
        productionTypeList
    } from '../../../utils/jk/status-option-list';
    export default {
        name: 'ProductionNoticeOrder',
        components: {
        },
        mixins: [calHeight, getMenuColumn, handlerCache],
        data() {
            return {
                apiItem: {
                    'page': productionProcessPrdNoticePage
                },
                prefix: 'production:prdNotice:process',
                productionTypeList: productionTypeList,
                priorityList: orderPriorityList,
                noticeStateList: noticeStateList,
                dataId: null,
                workshopList: [],
                processList: [],
                tableLoading: true,
                exportLoading: false,
                tableData: [],
                totalCount: 0,
                searchParams: {
                    pageNo: pageConfig.pageNo,
                    pageSize: pageConfig.pageSize,
                    productOrderCode: '',
                    productNameOrCode: '',
                    st: 1,
                    ifTest: false,
                    auditState: 1,
                    processCode: '',
                    selectItem: true,
                    workshopId: null
                },
                moreSearchParams: {
                    code: '',
                    batchCode: '',
                    priorityId: null
                },
                dropdownOption: [
                    { code: 'DETAIL', name: '详情', isShow: true, icon: 'el-icon-view', allowState: null, api: null },
                    { code: 'RELEASE', name: '下达', isShow: false, icon: 'el-icon-s-flag', allowState: 0, api: productionProcessPrdNoticeRelease },
                    { code: 'CANCEL_RELEASE', name: '撤销下达', isShow: true, icon: 'el-icon-circle-close', allowState: 1, api: productionProcessPrdNoticeClearRelease },
                    { code: 'FINISH', name: '已完成', isShow: true, icon: 'el-icon-check', allowState: null, api: productionProcessPrdNoticeComplete },
                    { code: 'UN_FINISH', name: '取消完成', isShow: true, icon: 'el-icon-close', allowState: 5, api: productionProcessPrdNoticeClearComplete },
                    { code: 'DELETE', name: '删除', isShow: true, icon: 'el-icon-delete', allowState: 0, api: productionProcessPrdNoticeDelete }
                ]
            };
        },
        methods: {
            onStateChange() {
                this.searchParams.pageNo = 1;
                this.getListRequest();
            },
            onPageChange(e, size) {
                this.$set(this.searchParams, 'pageNo', e);
                this.$set(this.searchParams, 'pageSize', size);
                this.getListRequest();
            },
            onResetSearchBtn() {
                Object.assign(this.$data.moreSearchParams, this.$options.data().moreSearchParams);
            },
            onDropdownChange(type, { id }) {
                const optionItem = this.dropdownOption.find(x => x.code === type);
                if (optionItem) {
                    if (optionItem.code === 'DETAIL') {
                        this.onDetailBtn({ id });
                    } else {
                        this.$confirm(`确定"${optionItem.name}"吗？`, '提示', { type: 'warning' }).then(() => {
                            optionItem.api({ id: id }).then(res => {
                                if (res.data.status === 200) {
                                    this.getListRequest();
                                }
                            });
                        }).catch(() => {});
                    }
                }
            },
            clearCacheMethod() {
                // Object.assign(this.$data, this.$options.data());
                this.$nextTick(() => {
                    this.getDependentData();
                });
            },
            getStateBarCountRequest() {
                this.noticeStateList.forEach(x => {
                    this.$set(x, 'count', 0);
                });
                return productionProcessPrdNoticeGetStateCount({
                    workshopId: this.searchParams.workshopId,
                    processCode: this.searchParams.processCode
                }).then(res => {
                    if (res.data.status === 200) {
                        this.noticeStateList = this.noticeStateList.map(x => {
                            x.count = 0;
                            res.data.res.forEach(k => {
                                if (x.id === k.auditState) {
                                    this.$set(x, 'count', k.count);
                                }
                            });
                            return x;
                        });
                    }
                });
            },
            onDetailBtn(row) {
                this.dataId = row.id;
                this.$toOtherRouter({
                    name: 'detailProductionNoticeOrder',
                    query: {
                        id: row.id
                    }
                });
            },
            /** 查询列表 */
            getListRequest() {
                this.tableLoading = true;
                const params = { ...JSON.parse(JSON.stringify(this.moreSearchParams)), ...JSON.parse(JSON.stringify(this.searchParams)) };
                params.auditStates = [this.searchParams.auditState];
                delete params.auditState;
                return this.apiItem['page'](params).then(res => {
                    this.tableLoading = false;
                    this.getStateBarCountRequest();
                    if (res.data.status === 200) {
                        this.tableData = res.data.res;
                        this.totalCount = res.data.count;
                    }
                });
            },
            /** 搜索按钮操作 */
            onSearchBtn() {
                this.searchParams.pageNo = 1;
                this.totalCount = 1;
                this.getListRequest();
            },
            /** 新增按钮操作 */
            onAddBtn() {
                this.$toOtherRouter({ name: 'addForeSpinningPlan' });
            },
            /** 修改按钮操作 */
            onEditBtn(row) {
                this.dataId = row.id;
                this.$toOtherRouter({
                    name: 'editProductionNoticeOrder',
                    query: {
                        id: row.id
                    }
                });
            },

            /** 删除按钮操作 */
            onDeleteBtn(row) {
                this.apiItem['delete']({ id: row.id }).then((res) => {
                    if (res.data.status === 200) {
                        this.getListRequest();
                        this.$tipsBar(this, 'delete');
                    }
                }).catch(() => {});
            },
            /** 导出按钮操作 */
            onReportBtn() {
                const params = { ...this.searchParams };
                params.pageNo = null;
                params.pageSize = 1000;
                this.$confirm('是否确认导出所有数据项?', { type: 'warning' }).then(() => {
                    this.exportLoading = true;
                    return this.apiItem['page'](params);
                }).then(res => {
                    this.exportLoading = false;
                    if (res.data.status === 200) {
                        import('@/vendor/Export2Excel').then(excel => {
                            const tHeader = ['规格', '批号', '粗纱', '氨纶', '芋管', '纸管', '机台'];
                            const filterVal = ['productName', 'batchCode', 'cuSha', 'anLun', 'yuGuan', 'zhiGuan', 'machineList'];
                            let list = JSON.parse(JSON.stringify(res.data.res)).map(item => {
                                item.isSort = 0;
                                if (item.batchCode.charAt(0).toUpperCase() === 'B') {
                                    item.isSort = 1;
                                }
                                item.machineList = item.prdNoticeMachineList.map(x => x.machineName);
                                item.cuSha = item.productOrder.coarseSandList ? item.productOrder.coarseSandList.filter(x => x.typeName === '粗纱').map(x => x.productName).join(' , ') : '';
                                item.anLun = item.productOrder.coarseSandList ? item.productOrder.coarseSandList.filter(x => x.typeName === '氨纶').map(x => x.productName).join(' , ') : '';
                                item.yuGuan = item.spunYarnColors ? item.spunYarnColors.map(x => x.name) : '';
                                item.zhiGuan = item.productOrder.paperTubeList ? item.productOrder.paperTubeList.map(x => x.name).join(' , ') : '';
                                return item;
                            });
                            list = list.sort((a, b) => {
                                return b.isSort - a.isSort;
                            });
                            const data = list.map(v => filterVal.map(j => {
                                return v[j];
                            }));
                            excel.export_json_to_excel({
                                header: tHeader,
                                data,
                                filename: this.$route.meta.title,
                                autoWidth: true,
                                bookType: 'xlsx'
                            });
                        });
                    }
                }).catch(() => {});
            },
            async getDependentData() {
                this.tableLoading = true;
                await this.getMenuColumnListRequest();
                await this.getListRequest();
                this.tableLoading = false;
            }
        },
        mounted() {
            this.processList = this.$store.state.user.userProcess.processList;
            this.workshopList = this.$store.state.user.userWorkshop.workshopList;
            if (!this.searchParams.workshopId) {
                this.$set(this.searchParams, 'workshopId', this.$store.state.user.userWorkshop.defaultWorkshopId);
            }
            if (!this.searchParams.processCode) {
                this.$set(this.searchParams, 'processCode', this.$store.state.user.userProcess.defaultProcessCode);
            }
            this.getDependentData();
        }
    };
</script>
